<template>
	<view class="poster">
		<!-- 海报内容容器，用于canvas绘制 -->
		<view class="poster-content" id="posterContent">
			
			<view class="task-address">
				<view class="address-content">
					<view class="task-address_avatar">
						<image class="avatarimg" v-if="userstore.userInfo.avatar!=''"
							:src="baseImgurl+'/'+userstore.userInfo.avatar" mode="aspectFill"></image>
					</view>
					<view class="user-info">
						<view class="username">{{userstore.userInfo.username}}</view>
					</view>
				</view>
			</view>

			
			<image class="poster-img" :src="qrcodeImage" mode="widthFix"></image>


		</view>

		<view class="btn" @click="savePoster">
			保存海报
		</view>
		<canvas 
		  canvas-id="posterCanvas" 
		  id="posterCanvas"
		  style="width: 750rpx; height: 1334rpx; position: fixed; left: -9999px;"
		></canvas>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		onLoad,
	} from "@dcloudio/uni-app";
	import {
		useUserStore
	} from '@/store/modules/user.js'
	import {
		throttle
	} from '@/utils/utils.js'
	import {
		reactive
	} from "@vue/runtime-dom";
	const userstore = useUserStore()
	const qrcodeImage = ref('')
	const baseImgurl = ref('')
	const userInfo = reactive({
		avatar: '',
		username: ""
	})
	onMounted(() => {
		baseImgurl.value = uni.getStorageSync('baseUrl')
	})
	onLoad(async () => {
		let res = await userstore.getQrcode()
		if (res.code == 200) {
			qrcodeImage.value = uni.getStorageSync('baseUrl') + '/' + res.data.qrcode
		}
		let info = JSON.parse(uni.getStorageSync('user'));
		if (info && info.userInfo) {
			let data = await userstore.visitShareCount({
				share_user_id: info.userInfo.id
			})


		} else {
			console.error('User info not found in storage:', info);
		}


	})
	// const save = throttle(() => {
	// 	uni.downloadFile({
	// 		url: qrcodeImage.value,
	// 		success: (res) => {
	// 			if (res.statusCode == 200) {
	// 				uni.saveImageToPhotosAlbum({
	// 					filePath: res.tempFilePath,
	// 					success: function() {
	// 						uni.$uv.toast('保存成功')
	// 					},
	// 					fail: (err) => {
	// 						uni.$uv.toast('保存失败')
	// 					}
	// 				});
	// 			}
	// 		}
	// 	})
	// }, 200)
	// / 保存海报
const savePoster = throttle(async () => {
  uni.showLoading({ title: '生成海报中...', mask: true })
  
  try {
    // 1. 处理图片路径
    const avatarUrl = baseImgurl.value + '/' + userstore.userInfo.avatar
    const qrcodeUrl = qrcodeImage.value.replace('http://', 'https://')
    
    // 2. 加载所有图片
    const [avatarInfo, qrcodeInfo] = await Promise.all([
      loadImage(avatarUrl),
      loadImage(qrcodeUrl)
    ])
    
    // 3. 创建canvas上下文
    const canvasContext = uni.createCanvasContext('posterCanvas', this)
    const canvasWidth = 750
    const canvasHeight = 1334
    
    // 4. 绘制背景（白色）
    canvasContext.setFillStyle('#ffffff')
    canvasContext.fillRect(0, 0, canvasWidth, canvasHeight)
    
    // 7. 绘制二维码（关键添加）
    const qrSize = 370 // 二维码尺寸
    const qrX = (canvasWidth - qrSize) / 2 // 水平居中
    const qrY = 50 // 垂直位置
    canvasContext.drawImage(qrcodeInfo.path, 10, 0, 375, 700)
    
    // 5. 绘制头像（圆形）
    try {
      const avatarSize = 36
      const avatarX = 60
      const avatarY = 425
      
      canvasContext.save()
      canvasContext.beginPath()
      canvasContext.arc(avatarX + avatarSize/2, avatarY + avatarSize/2, avatarSize/2, 0, 2 * Math.PI)
      canvasContext.clip()
      canvasContext.drawImage(avatarInfo.path, avatarX, avatarY, avatarSize, avatarSize)
      canvasContext.restore()
    } catch (e) {
      console.warn('头像绘制失败:', e)
    }
    
    // 6. 绘制用户名（关键添加）
    canvasContext.setFontSize(14)
    canvasContext.setFillStyle('#000000')
    canvasContext.fillText(userstore.userInfo.username, 120, 460) // x=200,y=140
   
    // 8. 绘制完成（使用同步绘制）
    canvasContext.draw(true)
    
    // 9. 生成图片文件
    await new Promise(resolve => setTimeout(resolve, 300)) // 等待绘制完成
    const res = await new Promise((resolve, reject) => {
      uni.canvasToTempFilePath({
        canvasId: 'posterCanvas',
        success: resolve,
        fail: reject
      }, this)
    })
    
    // 10. 保存到相册
    await new Promise((resolve, reject) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: resolve,
        fail: reject
      })
    })
    
    uni.hideLoading()
    uni.showToast({ title: '保存成功', icon: 'success' })
    
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ 
      title: `生成失败: ${err.message || err.errMsg || '未知错误'}`,
      icon: 'none',
      duration: 3000
    })
    console.error('海报生成错误:', err)
  }
}, 1000)

	// 辅助函数：加载图片
	const loadImage = (src) => {
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: src,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			})
		})
	}
</script>

<style lang="scss" scoped>
	.poster {
		width: 100%;
		padding: 30rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.poster-img {
		width: 690rpx;
		position: relative;
		z-index: 1;
	}

	.btn {
		margin: 50rpx auto 0;
		width: 200rpx;
		height: 80rpx;
		background: #4CAF50;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 40rpx;
		font-size: 28rpx;
	}

	.task-address {
		position: absolute;
		z-index: 2;
		width: 200rpx;
		display: flex;
		justify-content: center;
		bottom: 38%;
		/* 调整这个值可以改变在图片上的垂直位置 */
		left: 18%;


	}

	.address-content {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-radius: 50rpx;

	}

	.avatarimg {
		width: 72rpx;
		height: 72rpx;
		border-radius: 50%;
	}




	.user-info {
		padding-left: 20rpx;
		max-width: 275rpx;

		.username {
			font-size: 28rpx;
			color: #000;
			font-weight: bold;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
</style>